package com.transmit.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

public class FileUtil {

    static final Logger logger = LogManager.getLogger(FileUtil.class);

    /**
     *
     * @return
     */
    public static String getProjectPath(){
        return System.getProperty("user.dir");
    }

    public static String getServerPath() {
        String projectPath = getProjectPath();
        File projectFile = new File(projectPath);
        return projectFile.getParentFile().getAbsolutePath();
    }

    public static String getTempFilePath(){
        String serverPath = getServerPath();
        return serverPath + File.separator + "temp";
//        return "D:\\work\\Light3dServer\\temp";
    }

    public static String getFilePath() {
        String serverPath = getServerPath();
        return serverPath + File.separator + "files" + File.separator;
//        return "D:\\work\\Light3dServer\\temp";
    }

    public static String getUtilPath(){
        String serverPath = getServerPath();
        return serverPath + File.separator + "util";
    }


    public static byte[] getBytesFromFile(File file){
        ByteArrayOutputStream bos = null;
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
            bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = in.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            data = bos.toByteArray();
            in.close();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (bos != null) {
                    bos.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return data;
    }

    public static byte[] getBytes(InputStream in){
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = in.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            byte[] data = bos.toByteArray();
            in.close();
            bos.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (bos != null) {
                    bos.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String getFileType(File file){
        if(!isEmpty(file)) {
            String fileName = file.getName();
            int index = fileName.lastIndexOf(".");
            if (index > 0) {
                return fileName.substring(++index);
            }
        }
        return null;
    }

    public static String getFileType(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        int index = fileName.lastIndexOf(".");
        if(index > 0) {
            return fileName.substring(++index);
        }
        return null;
    }

    public static String fname(String fileName) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        int randomNum = new Random().nextInt(1000);
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String realFileName = uuid + randomNum + fileType;
        return realFileName;
    }


    public static boolean isEmptyRow(Row row) {
        if (row == null || row.toString().isEmpty()) {
            return true;
        } else {
            boolean isEmpty = true;
            // 从第一个不为空的列开始 到 最后一个 不为空的列(有格式就算一列 )
            for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
                Cell cell = row.getCell(c);
                if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK){
                    isEmpty = false;
                    break;
                }
            }
            return isEmpty;
        }
    }

    //文件校验是否为空
    public static boolean isEmpty(File file){
        return file == null || !file.exists();
    }

    public static File saveFile(InputStream inputStream, String fileName, String fileType) throws IOException {
        String saveDirectoryPath = getTempFilePath();
        if(org.springframework.util.StringUtils.isEmpty(fileName)) {
            fileName = UUID.randomUUID().toString().replaceAll("-", "") + fileType;
        }
        File file = new File(saveDirectoryPath, fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        OutputStream outputStream = new FileOutputStream(file);
        FileUtil.writeToFile(inputStream, outputStream);
        return file;
    }

    public static void writeToFile(InputStream in, OutputStream out) throws IOException {
        //读写文件
        int len = 0;
        byte[] buffer = new byte[1024];
        while((len=in.read(buffer))!=-1){
            out.write(buffer, 0, len) ;
        }
        in.close();
        out.close();
    }

    public static File unZipFile(File file) {
        if(!isEmpty(file)) {
            String unZipFileName = UUID.randomUUID().toString();
            File unZipFile = new File(file.getParentFile(), unZipFileName);
            if (!unZipFile.exists()) {
                unZipFile.mkdirs();
            }
            ZipFile zipFile = null;
            OutputStream out = null;
            InputStream in = null;
            try {
                zipFile = new ZipFile(file, "gbk");
                Enumeration zList = zipFile.getEntries();
                //共用变量
                ZipEntry ze;
                File destFile;
                //解压文件数量
                int numOfUnzipFile = 0;

                //解压缩
                while (zList.hasMoreElements()) {
                    //获取ZipEntry
                    ze = (ZipEntry) zList.nextElement();
                    //跳过文件夹
                    if (ze.isDirectory()) {
                        continue;
                    }
                    //目标解压文件
                    System.out.println(ze.getName());
                    destFile = new File(unZipFile, ze.getName());

                    if (!destFile.getParentFile().exists()) {
                        destFile.getParentFile().mkdirs();
                    }
                    //输入输出流
                    out = new FileOutputStream(destFile);
                    in = zipFile.getInputStream(ze);

                    //读写文件
                    int len = 0;
                    byte[] buffer = new byte[10240];
                    while ((len = in.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                    }
                    //关闭流
                    in.close();
                    out.close();
                    //打印日志
                    logger.info("unzip file : " + numOfUnzipFile++ + ": " + ze.getName());
                }
                //删除文件
                zipFile.close();
                return unZipFile;
            }catch (Exception e){
                logger.error(e.getMessage());
            }finally {
                if(zipFile != null){
                    try {
                        zipFile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(in != null){
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(out != null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    public static File findFileBySuffix(File file, String suffix){
        if(!isEmpty(file)) {
            if (file.isDirectory()) {
                File resultFile;
                File[] files = file.listFiles();
                for (File fileItem : files) {
                    resultFile = findFileBySuffix(fileItem, suffix);
                    if (resultFile != null) {
                        return resultFile;
                    }
                }
            } else if (file.getName().endsWith(suffix)) {
                return file;
            }
        }
        return null;
    }

    public static boolean deleteDir(File dir) {
        boolean success = true;
        if(!isEmpty(dir)) {
            if (dir.isDirectory()) {
                //删除目录
                File[] files = dir.listFiles();
                boolean itemDelResult = true;
                //递归删除目录下文件
                for (File file : files) {
                    if(!deleteDir(file)){
                        itemDelResult = false;
                    }
                }
                // 目录此时为空，可以删除
                if(itemDelResult) {
                    success = dir.delete();
                }
            }else {
                // 删除文件
                success = dir.delete();
            }
        }
        return success;
    }

    public static String checkPoint(String str) {
//        str = "464000 790000, 464250 790000, 464250 790250, 464000 790250,464000 790000";
        String first = str.substring(0, str.indexOf(","));
        String last = str.substring(str.lastIndexOf(",") + 1, str.length());

        if (first.equals(last))
            return "1";
        else
            return first;
    }

    //string 转成 integer[]
    public static Integer[] convertToIntArray(String ids) {
        return (Integer[]) ConvertUtils.convert(ids.split(","), Integer.class);
    }

    //integer[] 转成 string
    public static String convertToString(Integer[] arr) {
        if (arr.length == 0)
            return "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; ) {
            sb.append(arr[i]);
            i++;
            if (i != arr.length) sb.append(",");
        }
        return sb.toString();
    }

    public static void main(String[] args) throws Exception {
//        System.out.println(getProjectPath());
//        System.out.println(getServerPath());
//        System.out.println(getFilePath());
        File file = new File("C:\\Users\\Administrator\\Desktop\\test.json");
//        System.out.println(file.getName());

        InputStream in = null;
        StringBuffer sb = new StringBuffer();
        if (file.isFile() && file.exists()) { //判断文件是否存在
            // 一次读多个字节
            byte[] tempbytes = new byte[1024];
            int byteread = 0;
            in = new FileInputStream(file);

            // 读入多个字节到字节数组中，byteread为一次读入的字节数
            while ((byteread = in.read(tempbytes)) != -1) {
                //  System.out.write(tempbytes, 0, byteread);
                String str = new String(tempbytes, 0, byteread);
                sb.append(str);
            }
//            System.out.println(sb);

            Map<Integer, String> map = Maps.newHashMap();
            JSONObject jo = JSONObject.parseObject(sb.toString());
            JSONArray features = jo.getJSONArray("features"); //找到features的json数组
            for (int i = 0; i < features.size(); i++) {
                JSONObject info = features.getJSONObject(i); // 获得features的第i个对象
                JSONObject geometry = info.getJSONObject("geometry");

                Object[] list  = (Object[]) geometry.getJSONArray("coordinates").toArray();  // 获得经纬度

                Object arr = list[0];

                String str = arr.toString().replace(",", " ");
                str = str.replace("] [", ",");
                str = str.replace("[", "");
                str = str.replace("]", "");
                System.out.println(str);

                map.put(i, str);
            }


            Set<Map.Entry<Integer, String>> comparSet = map.entrySet();
            for (Map.Entry<Integer, String> entry : comparSet) {
                Object object = map.get(entry.getKey());
                System.out.println(object);
            }

        } else {
            System.out.println("找不到指定的文件，请确认文件路径是否正确");
        }

    }

    public static String getStringRandom(int length) {
        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }




    /**
     {
         "features": [
             {
                 "geometry": {
                     "coordinates":
                        [
                            [
                                 [
                                     794000,
                                     468000
                                 ],
                                 [
                                     794000,
                                     464000
                                 ],
                                 [
                                     790000,
                                     464000
                                 ],
                                 [
                                     790000,
                                     468000
                                 ],
                                 [
                                     794000,
                                     468000
                                 ]
                             ]
                        ],
                    "type": "Polygon"
                 },
                 "type": "Feature",
                 "properties": {
                     "OBJECTID": 6,
                     "图幅号": "4",
                     "filename": "E46479000",
                     "SHAPE_Leng": 16000,
                     "SHAPE_Area": 16000000
                 }
             }
         ],
         "name": "10000",
         "type": "FeatureCollection"
     }

     */
}
